package com.ruoyi.web.controller.common.factory;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.web.core.SendSms;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码 工厂
 *
 * @author Jyl
 */
@Log4j2
@Component
public class CaptchaFactory
{
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    /**
     * 生成验证码 短信
     *
     * @param response
     * @param phone
     * @param tag
     * @return
     * @throws IOException
     */
    public AjaxResult sendCode(HttpServletResponse response, String phone, String tag) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID() + tag;
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String code = getRandom();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("phoneNumbers", phone);
        try
        {
            SendSms sendSms = new SendSms();
            sendSms.buildSendCaptcha(phone, code).send();

        } catch (ServiceException e)
        {
            throw new ServiceException(e.getMessage());
        } catch (Exception e)
        {
            log.error("验证码发送失败[captchaSms]: ", e);
            return AjaxResult.error("验证码发送失败");
        }
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        redisCache.setCacheObject(verifyKey + "json", jsonObject, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        return ajax;
    }

    private String getRandom()
    {
        Random random = new Random();
        int randomNum = random.nextInt(1000, 9999);
        return randomNum + "";
    }

}
